<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>进度监控</title>
</head>
<body>

<div id="progress"></div>
<script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>

<script>
<!--    xhr 实现 针对响应的进度-->
function response(options = {}) {
    const {url, method = 'GET', onProgress, data = null} = options
    return new Promise((resolve) => {
        const xhr = new XMLHttpRequest()
        xhr.addEventListener("readystatechange", () => {
            if (xhr.readyState === xhr.DONE) {
                resolve(xhr.responseText)
            }
        })
        xhr.addEventListener("progress", (e) => {
            console.log('传递的数据：{}，总的数据：{}', e.loaded, e.total)
            onProgress && onProgress({
                loaded: e.loaded,
                total: e.total
            })
        })
        xhr.open(method, url)
        xhr.send(data)
    })
}

//     xhr 针对请求的进度
function request(options={}){
    const {url,method='GET',onProgress,data=null} = options
    return new Promise((resolve)=>{
        const xhr = new XMLHttpRequest()
        xhr.addEventListener("readystatechange",()=>{
            if(xhr.readyState===xhr.DONE){
                resolve(xhr.responseText)
            }
        })
        xhr.upload.addEventListener("progress",(e)=>{
            console.log('传递的数据：{}，总的数据：{}',e.loaded,e.total)
            onProgress && onProgress({
                loaded:e.loaded,
                total:e.total
            })
        })
        xhr.open(method,url)
        xhr.send(data)
    })
}

//     fetch实现 针对响应的进度
function fetchResponse(options={}){
    const {url,method='GET',onProgress,data=null} = options
    return new Promise(async (resolve)=>{
       const resp = await fetch(url,{
           method,
           body:data
       })
        const total = +resp.headers.get("content-length")
        const decoder = new TextDecoder()

        let body = ''
        const reader = resp.body.getReader()
        let loaded = 0;
       while (1){
           const {done,value} = await  reader.read()
           if(done){
               break
           }
           loaded += value.length
           console.log(loaded,total)
           body += decoder.decode(value)
           onProgress&&onProgress({
               loaded,
               total
           })
       }
       resolve(body)
    })
}
</script>

</body>
</html>